﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Utility.Network
{
    public class Serializer
    {
        public Serializer()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        public static MemoryStream Serialize(object msg)
        {
            // To serialize the hashtable and its key/value pairs,  
            // you must first open a stream for writing. 
            // In this case, use a file stream.
            MemoryStream mStream = new MemoryStream();

            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(mStream, msg);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                
            }
            return mStream;
        }


        public static object DeSerialize(MemoryStream mStream)
        {
            object result = null;
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                // Deserialize the hashtable from the file and 
                // assign the reference to the local variable.
                result =  formatter.Deserialize(mStream);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
            }
            return result;
        }

        /*public static MemoryStream Serialize(object entity)
        {
            DataContractSerializer serializer = new DataContractSerializer(entity.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, entity);
                //return Encoding.UTF8.GetString(stream.ToArray());
                return stream;
            }
        }
        public static object DeSerialize(MemoryStream mStream, Type type)
        {
            DataContractSerializer serializer = new DataContractSerializer(type);
            return serializer.ReadObject(mStream);
        }
        public static object DeSerialize(string jsonstring, Type type)
        {
            DataContractSerializer serializer = new DataContractSerializer(type);
            using (MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)))
            {
                return serializer.ReadObject(mStream);
            }
        }*/

    }
}
